<?php
session_start();
require_once '../config.php';
require_once '../functions.php';

// 检查管理员是否登录
if (!is_admin_logged_in()) {
    header('Location: login.php');
    exit;
}

$message = '';
$message_type = '';

// 处理添加公告
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_announcement'])) {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $is_top = isset($_POST['is_top']) ? 1 : 0;
    
    if (empty($title) || empty($content)) {
        $message = '标题和内容不能为空';
        $message_type = 'error';
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO announcements (title, content, admin_id, is_top) VALUES (?, ?, ?, ?)");
            $stmt->execute([$title, $content, $_SESSION['admin_id'], $is_top]);
            $message = '公告添加成功';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = '添加失败，请重试';
            $message_type = 'error';
        }
    }
}

// 处理编辑公告
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_announcement'])) {
    $id = $_POST['id'] ?? 0;
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $is_top = isset($_POST['is_top']) ? 1 : 0;
    
    if (!is_numeric($id) || empty($title) || empty($content)) {
        $message = '参数错误或内容为空';
        $message_type = 'error';
    } else {
        $id = (int)$id;
        
        try {
            $stmt = $pdo->prepare("UPDATE announcements SET title = ?, content = ?, is_top = ? WHERE id = ?");
            $stmt->execute([$title, $content, $is_top, $id]);
            $message = '公告修改成功';
            $message_type = 'success';
        } catch (PDOException $e) {
            $message = '修改失败，请重试';
            $message_type = 'error';
        }
    }
}

// 处理操作
if (isset($_GET['action'])) {
    $id = $_GET['id'] ?? 0;
    if (!is_numeric($id)) {
        $message = '参数错误';
        $message_type = 'error';
    } else {
        $id = (int)$id;
        switch ($_GET['action']) {
            case 'delete':
                // 删除公告
                try {
                    $stmt = $pdo->prepare("DELETE FROM announcements WHERE id = ?");
                    $stmt->execute([$id]);
                    $message = '删除成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '删除失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            case 'top':
                // 置顶公告
                try {
                    $stmt = $pdo->prepare("UPDATE announcements SET is_top = 1 WHERE id = ?");
                    $stmt->execute([$id]);
                    $message = '置顶成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '置顶失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            case 'untop':
                // 取消置顶
                try {
                    $stmt = $pdo->prepare("UPDATE announcements SET is_top = 0 WHERE id = ?");
                    $stmt->execute([$id]);
                    $message = '取消置顶成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '取消置顶失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            default:
                $message = '无效操作';
                $message_type = 'error';
                break;
        }
    }
}

// 获取公告列表
$stmt = $pdo->query("SELECT a.*, ad.username FROM announcements a 
                    JOIN admins ad ON a.admin_id = ad.id 
                    ORDER BY a.is_top DESC, a.created_at DESC");
$announcements = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公告管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../static/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/css/all.min.css">
    <link rel="stylesheet" href="../static/css/style.css">
</head>
<body>
    <div class="sidebar col-md-3 col-lg-2 d-md-block">
        <div class="sidebar-header">
            <h2><?php echo SITE_NAME; ?> 管理后台</h2>
        </div>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-tachometer-alt"></i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="confessions.php">
                    <i class="fas fa-heart"></i> 表白管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="dailies.php">
                    <i class="fas fa-coffee"></i> 日常管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="announcements.php">
                    <i class="fas fa-bullhorn"></i> 公告管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="comments.php">
                    <i class="fas fa-comments"></i> 评论管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="prohibited_words.php">
                    <i class="fas fa-ban"></i> 违禁词管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="banned_ips.php">
                    <i class="fas fa-shield-alt"></i> 封禁管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="settings.php">
                    <i class="fas fa-cog"></i> 系统设置
                </a>
            </li>
        </ul>
        
        <div class="logout-btn">
            <a href="logout.php">
                <i class="fas fa-sign-out-alt"></i> 退出登录
            </a>
        </div>
    </div>
    
    <main class="main-content">
        <h1 class="page-title"><i class="fas fa-bullhorn"></i> 公告管理</h1>
        
        <?php if (!empty($message)): ?>
            <div class="message message-<?php echo $message_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <!-- 添加公告表单 -->
        <div class="card">
            <h2 class="card-title"><i class="fas fa-plus-circle"></i> 添加新公告</h2>
            <form method="post">
                <div class="form-group">
                    <label class="form-label" for="title">公告标题</label>
                    <input type="text" class="form-control" id="title" name="title" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="content">公告内容</label>
                    <textarea class="form-control" id="content" name="content" required></textarea>
                </div>
                
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="is_top" name="is_top">
                    <label class="form-check-label" for="is_top">置顶公告</label>
                </div>
                
                <button type="submit" name="add_announcement" class="btn btn-primary">发布公告</button>
            </form>
        </div>
        
        <!-- 公告列表 -->
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>内容</th>
                        <th>发布人</th>
                        <th>发布时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($announcements) > 0): ?>
                        <?php foreach ($announcements as $announcement): ?>
                            <tr>
                                <td><?php echo $announcement['id']; ?></td>
                                <td><?php echo htmlspecialchars($announcement['title']); ?></td>
                                <td><?php echo mb_strlen($announcement['content']) > 30 ? mb_substr($announcement['content'], 0, 30) . '...' : htmlspecialchars($announcement['content']); ?></td>
                                <td><?php echo htmlspecialchars($announcement['username']); ?></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($announcement['created_at'])); ?></td>
                                <td><?php echo $announcement['is_top'] ? '<span class="badge badge-top">已置顶</span>' : ''; ?></td>
                                <td>
                                    <button class="action-btn btn-edit" onclick="openEditModal(
                                        <?php echo $announcement['id']; ?>, 
                                        '<?php echo addslashes($announcement['title']); ?>', 
                                        '<?php echo addslashes($announcement['content']); ?>',
                                        <?php echo $announcement['is_top']; ?>
                                    )">
                                        <i class="fas fa-edit"></i> 编辑
                                    </button>
                                    <?php if ($announcement['is_top']): ?>
                                        <a href="announcements.php?action=untop&id=<?php echo $announcement['id']; ?>" class="action-btn btn-untop" onclick="return confirm('确定要取消置顶吗？')">
                                            <i class="fas fa-thumbtack"></i> 取消置顶
                                        </a>
                                    <?php else: ?>
                                        <a href="announcements.php?action=top&id=<?php echo $announcement['id']; ?>" class="action-btn btn-top" onclick="return confirm('确定要置顶吗？')">
                                            <i class="fas fa-thumbtack"></i> 置顶
                                        </a>
                                    <?php endif; ?>
                                    <a href="announcements.php?action=delete&id=<?php echo $announcement['id']; ?>" class="action-btn btn-delete" onclick="return confirm('确定要删除吗？此操作不可恢复！')">
                                        <i class="fas fa-trash"></i> 删除
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" style="text-align: center; padding: 20px;">暂无公告内容</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>
    
    <!-- 编辑模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeEditModal()">&times;</span>
            <h2 class="modal-title">编辑公告</h2>
            <form method="post">
                <input type="hidden" id="editId" name="id">
                
                <div class="form-group">
                    <label class="form-label" for="editTitle">公告标题</label>
                    <input type="text" class="form-control" id="editTitle" name="title" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="editContent">公告内容</label>
                    <textarea class="form-control" id="editContent" name="content" required></textarea>
                </div>
                
                <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="editIsTop" name="is_top">
                    <label class="form-check-label" for="editIsTop">置顶公告</label>
                </div>
                
                <button type="submit" name="edit_announcement" class="btn btn-primary">保存修改</button>
            </form>
        </div>
    </div>
    
    <script>
        // 编辑模态框相关
        const modal = document.getElementById('editModal');
        
        function openEditModal(id, title, content, isTop) {
            document.getElementById('editId').value = id;
            document.getElementById('editTitle').value = title;
            document.getElementById('editContent').value = content;
            document.getElementById('editIsTop').checked = isTop === 1;
            modal.style.display = 'flex';
        }
        
        function closeEditModal() {
            modal.style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>
